package com.mingqijia.gassafety.job.job;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.mingqijia.gassafety.db.entity.RecordController;
import com.mingqijia.gassafety.db.entity.RecordDetector;
import com.mingqijia.gassafety.db.entity.RecordDtu;
import com.mingqijia.gassafety.db.entity.RecordReceiverValve;
import com.mingqijia.gassafety.job.service.*;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.utils.RedisCacheExt;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.CollectionUtils;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author guoliang.lao
 * @version 1.0.0
 * @ClassName RecordJob.java
 * @Description 上报数据处理
 * @createTime 2023年10月09日
 */
@Configuration
@EnableScheduling
@Slf4j
public class DeviceRecordJob {

    @Autowired
    RedisCacheExt redisUtil;
    @Autowired
    RecordControllerService recordControllerService;
    @Autowired
    RecordDetectorService recordDetectorService;
    @Autowired
    RecordReceiverValveService recordReceiverValveService;
    @Autowired
    RecordDtuService recordDtuService;

    /**
     * 处理上报数据到history表
     */
    @Scheduled(cron = "${gassafety.job.record.handle}")
    public void deviceRecordHandle() {
        log.info("deviceRecordHandle--start--------");
        String key = Constants.DEVICE_RECORD_HANDLE;
        Boolean acquire = redisUtil.setIfAbsent(key, String.valueOf(System.currentTimeMillis()), Constants.TIME_OUT);//15分钟超时
        if (acquire) {
            try {
                //每月的第一天，删除上一年的数据
                LocalDate today = LocalDate.now();  // 获取当前日期
                if (today.getDayOfMonth() == 1) {
                    int value = today.getMonth().getValue();
                    String month;
                    if (value < 10) {
                        month = "0" + value;
                    } else {
                        month = String.valueOf(value);
                    }
                    log.info("每月的第一天，删除上一年的数据,delList:{}",month);
                    recordControllerService.deleteRecordHistory(month);
                }

                //每天把上报的数据备份到history表
                LocalDateTime yesterday = LocalDateTime.now().minus(1, ChronoUnit.DAYS);
                // 获取前一天的0点0分0秒
                LocalDateTime startOfDay = yesterday.toLocalDate().atStartOfDay();
                // 获取前一天的23点59分59秒
                LocalDateTime endOfDay = startOfDay.plus(Duration.ofHours(23).plusMinutes(59).plusSeconds(59));
                log.info("每天把上报的数据备份到history表,start:{},end:{}",startOfDay,endOfDay);
                int page = 0;
                int pageSize = 500;
                 //查询控制器上报记录
                List<RecordController> list = recordControllerService.getListByTime(page,pageSize,startOfDay.toString(),endOfDay.toString(), 0);
                if (!CollectionUtils.isEmpty(list)) {
                    List<Long> ids = list.stream().map(RecordController::getId).collect(Collectors.toList());
                    log.info("需要备份的ids:"+ids);
                    //查询控制器上报记录对应的探头，设备，电磁阀记录列表
                    List<RecordDetector> detectorList = recordDetectorService.getListByRecordId(ids);
                    List<RecordReceiverValve> receiverList = recordReceiverValveService.getListByRecordId(ids);
                    List<RecordDtu> dtuList = recordDtuService.getListByRecordId(ids);
                    for (RecordController recordController : list) {
                        recordControllerService.deviceRecordHandle(recordController,
                                detectorList.stream().filter(a->a.getRecordId().equals(recordController.getId())).collect(Collectors.toList()),
                                receiverList.stream().filter(a->a.getRecordId().equals(recordController.getId())).collect(Collectors.toList()),
                                dtuList.stream().filter(a->a.getRecordId().equals(recordController.getId())).collect(Collectors.toList()),page);
                    }
                    recordControllerService.deleteRecord(ids, detectorList, receiverList, dtuList, page);
                    while (!list.isEmpty()) {
                        //查询控制器上报记录
                        list = recordControllerService.getListByTime(page,pageSize,startOfDay.toString(),endOfDay.toString(), 0);
                        if (!CollectionUtils.isEmpty(list)) {
                            //查询控制器上报记录对应的探头，设备，电磁阀记录列表
                            List<Long> ids2 = list.stream().map(RecordController::getId).collect(Collectors.toList());
                            log.info("需要备份的ids:"+ids2);
                            List<RecordDetector> detectorList2 = recordDetectorService.getListByRecordId(ids2);
                            List<RecordReceiverValve> receiverList2 = recordReceiverValveService.getListByRecordId(ids2);
                            List<RecordDtu> dtuList2 = recordDtuService.getListByRecordId(ids2);
                            for (RecordController recordController : list) {
                                recordControllerService.deviceRecordHandle(recordController,
                                        detectorList2.stream().filter(a->a.getRecordId().equals(recordController.getId())).collect(Collectors.toList()),
                                        receiverList2.stream().filter(a->a.getRecordId().equals(recordController.getId())).collect(Collectors.toList()),
                                        dtuList2.stream().filter(a->a.getRecordId().equals(recordController.getId())).collect(Collectors.toList()),page);
                            }
                            recordControllerService.deleteRecord(ids2, detectorList2, receiverList2, dtuList2, page);
                        }
                    }
                }

            } catch (Exception e) {
                log.info("getOrderStatus-error:{}", e);
            } finally {
                redisUtil.del(key);
            }
        } else {
            log.info("deviceRecordHandle jog 加锁失败，不处理");
            return;
        }
        log.info("deviceRecordHandle--end--------");
    }
}
